<template>
<div class="high advanced-search advanced-search-1">
  <div class="popover"
    :class="{
      moving: moving,
      dialogVisible: dialogVisible
    }"
    v-show="opened"
  >
    <button class="config-button" @click="handleSearchConfig">
      <i class="iconfont icon-peizhi"/>
      <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.advancedSearchCustomLayout">
        <div class="novice-circle-group " style="position: absolute;top: -35px;right: -15px;cursor: default;">
          <div class="novice-circle4"></div>
          <div class="novice-circle3"></div>
          <div class="novice-circle2"></div>
          <div class="novice-circle1"></div>
        </div>
        <div style="position: absolute;top: -112px;left:-112px ;padding-bottom: 10px;z-index: 100;cursor: default;">
          <novice-boot
            NoviceKey="advancedSearchCustomLayout"
            :NoviceArr="[{title: '', text: $t('public.searchSettingsNovice1')}]"
            @updateGuidanceSuccess="updateGuidanceSuccess"
          ></novice-boot>
        </div>
      </div>
    </button>
    <!-- <div class="form-mark" v-if="dialogVisible"></div> -->
    <el-form class="high-ranking-search" ref="ruleForm"
      :inline="true" label-position="top"
      :rules="computeRules"
      :model="formStacked.form"
    >
      <div class="search-condition">
        <div class="default-form">
          <template v-for="(item,index) in dealedFormItems">
            <el-form-item
              v-if="item._type === '_localed'"
              :key="item.name"
              :label="item.label"
              :prop="item.name"
              :class="[
                item.inputType === 'time' || item.inputType === 'radioInput' ? 'add-width' : '',
                item.inputType === 'multi' ? 'multi-label' : '',
                item.inputType === 'rangeInput' ? 'cdr-call': '',
                item.inputType === 'area' ? 'add-width-linkage': '',
                item.name ==='CALL_TIME_LENGTH_END' || item.name === 'QUEUE_TIME_LENGTH_END' || item.name === 'RING_TIME_LENGTH_END'?'whiteFont':'',
                item.name ==='ownercom'?'ownercom':'',
                item.inputType === 'no' ? 'minus-width' : '',
                item.name === currentItemName ||
                (item.name && item.name.replace('_END','_BEGIN') === currentItemName) ||
                (item.name && item.name.replace('_BEGIN','_END') === currentItemName)
                ? 'current-item' : ''
              ]"
            >
              <div class="mark" v-if="dialogVisible" @click="currentItemName=item.name">
                <!-- <div class="sequence">{{index | sequence}}</div> -->
              </div>
              <span class="offerTimeWarn"
                v-if="item.name === 'OFFERING_TIME' && callTimeLimit > 0"
                v-html="$t('call.offerTimeWarn', {calltimeLimit: callTimeLimit})"
              ></span>
              <span class="offerTimeWarn"
                v-if="item.name === 'createTime' && isWebchat">{{$t('public.searchCreateTimeLimit')}}</span>
              <area-linkage ref="areaLinkage"
                v-if="item.inputType==='area'"
                :isMerge="true"
                :isSearch="true"
                :provinceName="item.provinceName"
                :cityName="item.cityName"
                :provinceValue="formStacked.form[item.provinceName]"
                :cityValue="formStacked.form[item.cityName]"
                :districtValue="formStacked.form[item.districtName]"
                @valueChange="changeData"
              ></area-linkage>

              <el-input size="mini"
                v-if="item.inputType==='input'"
                v-model.trim="formStacked.form[item.name]"
                :placeholder="item.placehoder?item.placehoder:''"
                @blur="valueFiter(item.name)"
              ></el-input>

              <template v-if="item.inputType==='rangeInput'">

                <el-input style="width:90%" size="mini"
                  v-model.trim="formStacked.form[item.name]"
                  :placeholder="$t('public.pleaseEnter')"
                >
                  <template slot="append">{{$t('public.seconds')}}</template>
                </el-input>

                <span class="public-to"
                  v-if="
                    item.name !== 'CALL_TIME_LENGTH_END' &&
                    item.name !== 'RING_TIME_LENGTH_END' &&
                    item.name !== 'QUEUE_TIME_LENGTH_END'
                  "
                >{{$t('public.to')}}</span>

              </template>

              <el-autocomplete class="inline-input" style="width:100%"
                v-if="item.inputType==='serverNo'"
                v-model.trim="formStacked.form[item.name]"
                :fetch-suggestions="(queryString, callback) => querySearchServerNo(queryString, callback, item.type)"
                :trigger-on-focus="true"
                @select="handleSelect"
              ></el-autocomplete>

              <el-select size="mini"
                v-if="item.inputType==='select'"
                v-model.trim="formStacked.form[item.name]"
                :multiple="item.multiple"
                :allow-create="item.allowCreate"
                :filterable="item.filterable"
                :collapse-tags="item.collapseTags"
                :placeholder="$t('public.pleasePick')"
                @click.stop.native="remoteSearch(item.remoteMethod)"
                @change="changeData(formStacked.form[item.name], item.name)"
              >
                <el-option
                  v-for="(item2,index) in item.data"
                  :label="item2.label"
                  :value="item2.value"
                  :key="index"
                ></el-option>
              </el-select>
              <el-select size="mini"
                v-if="item.inputType==='selectDisabled'"
                v-model.trim="formStacked.form[item.name]"
                :multiple="item.multiple"
                :allow-create="item.allowCreate"
                :filterable="item.filterable"
                :collapse-tags="item.collapseTags"
                :placeholder="$t('public.pleasePick')"
                @click.stop.native="remoteSearch(item.remoteMethod)"
                @change="changeData(formStacked.form[item.name], item.name)"
              >
                <el-option
                  v-for="(item2,index) in item.data"
                  :label="item2.label"
                  :value="item2.value"
                  :disabled="item2.disabled"
                  :key="index"
                ></el-option>
              </el-select>
              <selectTree v-if="item.inputType==='selectTree'" @change='changeData' :model='formStacked.form[item.name]'></selectTree>
              <el-cascader
                 v-if = "item.inputType === 'cascader'"
                 :options="item.data"
                 filterable
                 v-model.trim="formStacked[item.name]"
                 :value = 'formStacked[item.name]'
                 change-on-select
                 @change="changeData(formStacked[item.name], item.name)"
               ></el-cascader>
              <el-cascader
                v-if = "item.inputType === 'multipleCascader'"
                :options="item.data"
                :disabled="item.disabled"
                filterable
                collapse-tags
                size="mini"
                v-model.trim="formStacked.form[item.name]"
                :props="{ multiple: true, checkStrictly: true}"
                @change="changeData(formStacked.form[item.name], item.name)"
                change-on-select
                clearable></el-cascader>
              <el-cascader
                 class="webchatFinish"
                 popper-class="webchat-finish"
                 v-if="item.inputType === 'webchatFinish' && endSessionLength >= 5000"
                 :clearable="true"
                 filterable
                 ref="webchatFinish"
                 :options="item.data"
                 :props="cascaderProps"
                 v-model.trim="formStacked.form[item.name]"
                 :value = 'formStacked[item.name]'
                 change-on-select
                 @change="changeData(formStacked.form[item.name], item.name)"
               ></el-cascader>
              <el-cascader
                 class="webchatFinish"
                 popper-class="webchat-finish"
                 v-if ="item.inputType === 'webchatFinish' && endSessionLength < 5000"
                 :clearable="true"
                 size="mini"
                 ref="webchatFinish"
                 :props="{ multiple: true, checkStrictly: false }"
                 :options="item.data"
                 filterable
                 v-model.trim="formStacked.form[item.name]"
                 :value = 'formStacked[item.name]'
                 change-on-select
                 @change="changeData(formStacked.form[item.name], item.name)"
               ></el-cascader>
              <el-date-picker size="mini" type="date" align="left"
                v-if="item.inputType==='date'"
                v-model.trim="formStacked.form[item.name]"
                :id="[item.name + '1', item.name + '2']"
                :editable="false"
                :placeholder="$t('public.pleasePick')"
                @focus="datePickerFocus"
                @blur = "datePickerBlur"
              ></el-date-picker>

              <el-date-picker size="mini" type="datetimerange" align="right" style="width:400px"
                v-if="item.inputType==='time'"
                v-model.trim="formStacked.form[item.name]"
                :id="[item.name + '3', item.name + '4']"
                :editable="false"
                :picker-options="pickerOptions2"
                :placeholder="$t('public.timeRanges')"
                :clearable="(item.name === 'OFFERING_TIME' || ((isWebchat || isShowOneDay) && item.name === 'createTime'))?false:true"
                :popper-class="(item.name === 'OFFERING_TIME' || ((isWebchat || isShowOneDay) && item.name === 'createTime'))?'hide-datetime-clear':''"
                @focus="datePickerFocus"
                @blur = "datePickerBlur"
              ></el-date-picker>

              <div v-if="item.inputType==='checkbox'">
                <el-checkbox-group  v-model.trim="formStacked.form[item.name]">
                  <el-checkbox
                    v-if="item.inputType==='checkbox'"
                    v-for="(item2,index) in item.data"
                    :label="item2.value"
                    :key="index"
                  >
                    {{item2.label}}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-if="item.inputType === 'radioInput'">
                <el-radio-group v-model.trim="formStacked.form[item.radioName]">
                  <el-radio size="mini" :label="`lt__${$t('webchat.lessThan')}`">{{$t('webchat.lessThan')}}</el-radio>
                  <el-radio size="mini" :label="`gt__${$t('webchat.moreThan')}`">{{$t('webchat.moreThan')}}</el-radio>
                  <el-radio size="mini" :label="`eq__${$t('webchat.equal')}`">{{$t('webchat.equal')}}</el-radio>
                </el-radio-group>
                <el-input size="mini" class="radioInputwidh" v-model.trim="formStacked.form[item.inputName]"></el-input>
              </div>

              <div v-if="item.inputType==='radio'">
                <el-radio-group  v-model.trim="formStacked.form.custom[item.name]">
                  <el-radio size="mini" v-if="item.inputType==='radio'"
                    v-for="(item2,index) in item.data"
                    :label="item2.value"
                    :key="index"
                  ></el-radio>
                </el-radio-group>
              </div>

              <i v-if="item.inputType==='no'"></i>

              <label-cascader
                v-if="item.inputType === 'multi'"
                :filterable="item.filterable ? true : false"
                :stringFlag="true"
                :resetSelect = 'resetSelect'
                :isClear="isClear"
                @labelSelect="changeData"
                :isNoLabel="true"
              ></label-cascader>

              <label-cascadermulti
                v-if="item.inputType === 'cascaderMulti'"
                :filterable="item.filterable ? true : false"
                :disabled="item.disabled"
                :stringFlag="true"
                :resetSelect = 'resetSelect'
                :isClear="isClear"
                @labelSelect="changeData"
                :isNoLabel="true"
              ></label-cascadermulti>

              <owner-tree-select ref="ownerTree"
                v-if="item.inputType === 'owner'"
                :businessType="type"
                :name="item.name"
                :owner="owner"
                @owner-change="handleOwnerChange"
                @owner-reset="handleOwnerReset"
              ></owner-tree-select>
                <el-tooltip class="robotSessionTip" effect="dark" :content="$t('webchat.robotSessionExplain')" placement="right-start">
                  <i class="icon iconfont icon-tishi" v-if="item.name === 'robotSession'"></i>
                </el-tooltip>
            </el-form-item>

            <el-form-item
              v-if="item._type === '_custom'"
              :key="item.name"
              :label="item.label"
              :class="[
                item.inputType==='time' || item.inputType==='date' || item.inputType==='datetime' || item.inputType == 'textarea' ? 'add-width' : '',
                item.inputType==='no' ? 'minus-width' : '',
                item.inputType==='checkbox' || item.inputType ==='radio' ? 'all-width' : '',
                item.name ===currentItemName?'current-item':''
              ]"
            >
              <div class="mark" v-if="dialogVisible" @click="currentItemName=item.name">
                <!-- <div class="sequence">{{index | sequence}}</div> -->
              </div>

              <el-input size="mini"
                v-if="item.inputType==='input'"
                v-model.trim="formStacked.form.custom[item.name]"
              ></el-input>

              <el-select size="mini"
                v-if="item.inputType==='select'"
                multiple
                collapse-tags
                v-model.trim="formStacked.form.custom[item.name].$in"
                :placeholder="$t('public.pleasePick')"
                @change="changeData(formStacked.form.custom[item.name], item.name, 'true', item.cascadeIndex)"
              >
                <el-option
                  v-for="(item2,index) in item.data" :key="index"
                  v-if="item.inputType==='select'"
                  :label="item2.label"
                  :value="item2.value"
                >
                </el-option>
              </el-select>

              <v-cascsder
                v-if="item.inputType==='cascader'"
                :optionsId="item.data.dicId"
                :initCascaderValue="formStacked.form.custom[item.name]"
                :formId="item.name"
                :props="item.props"
                :isSearch="true"
                @change="handleCascader"
              ></v-cascsder>

              <el-date-picker size="mini" type="daterange" align="right"
                v-if="item.inputType==='date'"
                style="width: 400px"
                v-model.trim="formStacked.form.custom[item.name]"
                :id="item.name + index"
                :editable="false"
                :picker-options="pickerOptions2"
                :placeholder="$t('public.pleasePick')"
                @focus="datePickerFocus"
                @blur = "datePickerBlur"
              ></el-date-picker>
              <el-date-picker size="mini" type="datetimerange" align="right"
                              v-if="item.inputType==='datetime'"
                              style="width: 400px"
                              v-model.trim="formStacked.form.custom[item.name]"
                              :id="item.name + index"
                              :editable="false"
                              :picker-options="pickerOptions2"
                              :placeholder="$t('public.timeRanges')"
                              @focus="datePickerFocus"
                              @blur="datePickerBlur"
              ></el-date-picker>
              <el-date-picker size="mini" type="datetimerange" align="right" style="width:400px"
                v-if="item.inputType==='time'"
                v-model.trim="formStacked.form.custom[item.name]"
                :id="item.name + index"
                :editable="false"
                :picker-options="pickerOptions2"
                :placeholder="$t('public.timeRanges')"
                @focus="datePickerFocus"
                @blur="datePickerBlur"
              ></el-date-picker>

              <div v-if="item.inputType==='checkbox'">
                <el-checkbox-group  v-model.trim="formStacked.form.custom[item.name]">
                  <el-checkbox
                    v-if="item.inputType==='checkbox'"
                    v-for="(item2,index) in item.data" :key="index"
                    :label="item2.value"
                  >
                    {{item2.label}}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-if="item.inputType==='radio'">
                <el-radio-group  v-model.trim="formStacked.form.custom[item.name]">
                  <el-radio size="mini"
                    v-if="item.inputType==='radio'"
                    v-for="(item2, index) in item.data" :key="index"
                    :label="item2.value"
                  >
                    {{item2.label}}
                  </el-radio>
                </el-radio-group>
              </div>

              <el-input size="mini" type="textarea"
                v-if="item.inputType==='textarea'"
                v-model="formStacked.form.custom[item.name]"
              ></el-input>

              <i v-if="item.inputType==='no'"></i>
            </el-form-item>
          </template>
        </div>
      </div>
      <el-form-item class="all-width btn-group footer-btn-group" style="z-index: 0">
        <el-button class="primary_btn rest-btn" :disabled="dialogVisible" @click="resetForm">{{$t("public.reset")}}</el-button>
        <el-button type="primary"  class="primary_btn" :disabled="dialogVisible" @click="submitForm('ruleForm')">{{$t("public.search")}}</el-button>
        <!-- <el-button type="primary"  class="primary_btn" :disabled="dialogVisible" @click="resetForm(); $refs.AdvancedSearchConfigDialog.open()">配置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
  <div @click.stop="toggle" class="toggle-btn" :class="disabled ? 'disabled' : ''">
    <el-tooltip class="item" effect="dark" :content="$t('public.advSearch')" placement="bottom">
      <i class="iconfont icon-gaojisousuo"></i>
    </el-tooltip>
  </div>
  <AdvancedSearchConfigDialog
    :searchType="'searchType'"
    ref="AdvancedSearchConfigDialog"
    :dialogVisible.sync="dialogVisible"
    :currentItemName.sync="currentItemName"
    :moving.sync="moving"
    :formItems="formItems"
    :activeName="activeName"
    :formItemsConfig="formItemsConfig"
    @confirmNewItemsConfig="$emit('confirmNewItemsConfig', $event)"
    @editingFormItemsConfigChange="editingFormItemsConfig = $event"
  />
</div>
</template>
<script>
  import {checkform} from '@/utils/validate'
  import AreaLinkage from '../../../ui-modules/area-linkage/AreaLinkage.vue'
  import OwnerTreeSelect from '../../agent-tree/OwnerTreeSelect.vue'
  import LabelCascader from '../../phone-bar/LabelCascader.vue'
  import LabelCascadermulti from '../../phone-bar/LabelCascaderMulti.vue'
  import Cascader from '../../cache/Cascader'
  import AdvancedSearchConfigDialog from './AdvancedSearchConfigDialog.vue'
  import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
  import { resetForm, deepClone, phoneFilterChats } from '@/utils/m7Utils.js'
  import selectTree from '../../../public-modules/select-tree/index.vue'
  export default {
    name: 'AdvancedSearch',
    /**
     * [props 该组件所需要的参数]
     * @type {
     *   type        业务类型
     *   typeType    业务tab
     * }
     */
    props: {
      type: String,
      searchType: String,
      activeName: String,
      adv: Object,
      isClear: Boolean,
      callServerNo: Array,
      isCall: Boolean,
      endSessionLength: {
        type: Number,
        default () {
          return 0
        }
      },
      disabled: {
        type: Boolean,
        default () {
          return false
        }
      },
      isWebchat: {
        type: Boolean,
        default () {
          return false
        }
      },
      isShowOneDay: {
        type: Boolean,
        default () {
          return false
        }
      },
      callTimeLimit: Number,
      formItemsConfig: {
        type: Object,
        default () {
          return null
        }
      }
    },
    data () {
      return {
        cascaderProps: {
          multiple: true,
          checkStrictly: false,
          lazy: true,
          lazyLoad: (node, resolve) => {
            setTimeout(() => {
              resolve()
            }, 30)
          },
          value: 'value',
          label: 'label',
          leaf: 'leaf'
        },
        owner1Item: {},
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
              const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
              picker.$emit('pick', [startTime, endTime])
            }
          }]
        },
        resetSelect: false,
        opened: false,
        emitData: {},
        editingFormItemsConfig: null,
        currentItemName: '',
        dialogVisible: false,
        moving: false,
        getNoviceKeyStatus: {},
        dateFocus: false,
        cascaderOptions: []
      }
    },
    watch: {
      opened (opened) {
        if (!opened) {
          this.$refs.AdvancedSearchConfigDialog.close()
        }
      }
    },
    components: {
      AreaLinkage,
      OwnerTreeSelect,
      'v-cascsder': Cascader,
      LabelCascader,
      AdvancedSearchConfigDialog,
      noviceBoot,
      selectTree,
      LabelCascadermulti
    },
    methods: {
      handleSearchConfig () {
        this.resetForm()
        this.$refs.AdvancedSearchConfigDialog.toggle()
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-高级搜索布局配置'])
      },
      valueFiter (key) {
        if (key !== 'phone') return
        this.formStacked.form.phone = phoneFilterChats(this.formStacked.form.phone)
      },
      submitForm (formName) {
        let self = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let form = self.formStacked.form
            if (form) {
              if (form.processMember === null || form.processMember === '') {
                self.$emit('ifRemark', false)
              } else {
                self.$emit('ifRemark', true)
              }
              if (parseInt(form.CALL_TIME_LENGTH_BEGIN) >= parseInt(form.CALL_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.callTimeError'))
                return
              } else if (parseInt(form.QUEUE_TIME_LENGTH_BEGIN) >= parseInt(form.QUEUE_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.queueTimeError'))
                return
              } else if (parseInt(form.RING_TIME_LENGTH_BEGIN) >= parseInt(form.RING_TIME_LENGTH_END)) {
                this.$message.error(this.$t('call.ringTimeError'))
                return
              }
              let offerTime = form.OFFERING_TIME
              if (offerTime && offerTime[0] && offerTime[1]) {
                let sTime = ''
                let eTime = ''
                if (typeof offerTime[0] === 'string') {
                  sTime = new Date(offerTime[0]).getTime()
                  eTime = new Date(offerTime[1]).getTime()
                } else {
                  sTime = offerTime[0].getTime()
                  eTime = offerTime[1].getTime()
                }
                let oneDay = 1000 * 3600 * 24
                let Days = parseInt((eTime - sTime) / oneDay)
                if (this.callTimeLimit > 0) { // 只有大于0的时候需要限制时间搜索范围，-1的情况不控制时间
                  if (Days > 31 * this.callTimeLimit) { // ss
                    this.$message.error(this.$t('call.callTimeLimitWarn', {calltimeLimit: this.callTimeLimit}))
                    return
                  }
                }
              }
              if (this.isWebchat){
                let createTime = form.createTime
                if (createTime && createTime[0] && createTime[1]) {
                  let sTime = ''
                  let eTime = ''
                  if (typeof createTime[0] === 'string') {
                    sTime = new Date(createTime[0]).getTime()
                    eTime = new Date(createTime[1]).getTime()
                  } else {
                    sTime = createTime[0].getTime()
                    eTime = createTime[1].getTime()
                  }
                  let oneDay = 1000 * 3600 * 24
                  let Days = parseInt((eTime - sTime) / oneDay)
                  if (Days > 31 * 12) { // ss
                    this.$message.error(this.$t('public.searchCreateTimeLimitNotice'))
                    return
                  }
                } else {
                  this.$message.error(this.$t('public.searchCreateTimeLimitNotice'))
                  return
                }
              }
            }
            // for( let item of self.emitData) {
            //   if (self.emitData[key] ===)
            // }
            // let newEmitData = fo    self.emitData.map(item => {
            //   if (typeof item === 'string') {
            //     return phoneFilterChats(item)
            //   }
            // })
            console.debug(self.EmitData)
            self.$emit('advSearch', false, 1, self.EmitData)
            document.getElementsByTagName('body')[0].click()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm () {
        this.resetSelect = true
        if (this.isCall) {
          this.$emit('restForm')
        } else {
          resetForm(this.formStacked.form)
        }
        if (this.$refs.areaLinkage && this.$refs.areaLinkage.length) {
          let obj = this.$refs.areaLinkage[0]
          obj.province = null
          obj.city = null
          obj.district = null
        }
        // if (this.formStacked['finishKey'] && this.formStacked['finishKey'])
        this.$refs.ruleForm.resetFields()
        //重置所有appraiseKeys数据值disabled恢复默认false
        let localed = JSON.parse(JSON.stringify(this.formStacked.advSearchOptions.localed))
        localed.forEach(i=>{
          if(i.name=='appraiseKeys'){
            i.data.forEach(it=>{
              it.disabled = false
            })
          }
        })
        this.formStacked.advSearchOptions.localed=localed
        if (this.formStacked.form.temp_id) {
          this.formStacked.form.temp_id = null
        }
        if (this.$refs.ownerTree && this.$refs.ownerTree.length) {
          this.$refs.ownerTree[0].$emit('resetValue')
        }
      },
      changeData (value, key, custom, cascadeIndex) {
        if (key === 'finishKey' && Array.isArray(value)) {
          if (value.length > 50) {
            if (this.$refs.webchatFinish && this.$refs.webchatFinish.length > 0) {
              this.$refs.webchatFinish[0].$refs.panel.clearCheckedNodes()
            }
            this.$message.error(this.$t('webchat.searchFinishTip'))
            return
          }
        }
        let emitData = {selectName: key, selectValue: value}
        if (key === 'multiCallLabel') {
          this.resetSelect = false
        }
        if (custom) {
          emitData.custom = true
          emitData.cascadeIndex = cascadeIndex
        }
        this.emitData = emitData
        this.$emit('selectChange', emitData)
      },
      handleCascader (data) {
        let emitData = { selectName: 'cascader', selectValue: data.val, name: data.id, custom: true }
        this.$emit('selectChange', emitData)
      },
      remoteSearch (methodName) {
        if (methodName) {
          this.$emit(methodName)
        }
      },
      handleOwnerChange (obj) {
        let emitData = { selectName: obj.type, selectValue: `${obj._id}__${obj.displayName || obj.label}`, name: obj.name }
        this.$emit('selectChange', emitData)
      },
      handleOwnerReset (name) {
        let emitData = { selectName: 'ownercom', selectValue: '' }
        if (name) {
          emitData.name = name
        }
        this.$emit('selectChange', emitData)
      },
      toggle () {
        if (this.disabled) {
          return
        }
        this.opened = !this.opened
      },
      querySearchServerNo (queryString, callback, type) {
        let restaurants = this.callServerNo
        let results = queryString ? restaurants.filter(this.createFilterServerNo(queryString, type)) : restaurants
        // 调用 callback 返回建议列表的数据
        callback(results)
      },
      createFilterServerNo (queryString, type) {
        return (restaurant) => {
          return (type ? (restaurant.value.indexOf(queryString) > -1) : (restaurant.value.indexOf(queryString.toLowerCase()) > -1))
        }
      },
      handleSelect (item) {
        if (this.formStacked.form.CALLED_NO) {
          let callEndIndex = this.formStacked.form.CALLED_NO.lastIndexOf(']')
          if (callEndIndex > 0) {
            this.formStacked.form.CALLED_NO = this.formStacked.form.CALLED_NO.substring(callEndIndex + 1, this.formStacked.form.CALLED_NO.length)
            // this.formStacked.form.CALLED_NO = this.formStacked.form.CALLED_NO.substring(0, callEndIndex)
          }
        }
        if (this.formStacked.form.CALL_NO) {
          let callIndex = this.formStacked.form.CALL_NO.lastIndexOf(']')
          if (callIndex > 0) {
            this.formStacked.form.CALL_NO = this.formStacked.form.CALL_NO.substring(callIndex + 1, this.formStacked.form.CALL_NO.length)
            // this.formStacked.form.CALL_NO = this.formStacked.form.CALL_NO.substring(0, callIndex)
          }
        }
      },
      clickFun (e) {
        if (!this.$el.contains(e.target) && !this.dateFocus) {
          this.opened = false
        }
      },
      updateGuidanceSuccess () {
        let guidance = this.$getCache('guidance')
        this.getNoviceKeyStatus = guidance || {'advancedSearchCustomLayout': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
      },
      datePickerFocus () {
        this.dateFocus = true
      },
      datePickerBlur () {
        this.dateFocus = false
      }
    },
    computed: {
      formStacked () {
        // 若高级搜索出现关于座席组件 单独提取 单独渲染
        // 解决之前循环中 v-if 座席数据较大是渲染过慢 页面假死的问题
        this.owner1Item = {}
        // this.adv.advSearchOptions.localed.filter((val) => {
        //   if (val.inputType === 'owner') {
        //     this.owner1Item = val
        //   }
        // })
        return this.adv
      },
      computeRules () {
        let validateMoblie = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Mobile')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let validateEmail = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Email')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let validateNum = (rule, value, callback) => {
          if (value !== '') {
            let match = checkform(value, 'Number3')
            if (match) {
              callback(new Error(this.$t(match)))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        let rules = {}
        let localItem = this.formStacked.advSearchOptions.localed
        if (localItem) {
          localItem.forEach((item) => {
            if (item.validateType === 'Number3') {
              rules[item.name] = [{validator: validateNum, trigger: 'blur'}]
            } else if (item.validateType === 'Mobile') {
              rules[item.name] = [{validator: validateMoblie, trigger: 'blur'}]
            } else if (item.validateType === 'Email') {
              rules[item.name] = [{validator: validateEmail, trigger: 'blur'}]
            }
          })
        }
        return rules
      },
      owner () {
        let form = deepClone(this.formStacked.form)
        let ownercom = form.ownercom ? form.ownercom : ''
        let owner = form.owner ? form.owner : ''
        let ownerdep = form.ownerdep ? form.ownerdep : ''

        // 工单特有的
        let ownercomCreateUser = form.ownercomCreateUser ? form.ownercomCreateUser : ''
        let createUser = form.createUser ? form.createUser : ''
        let ownerdepCreateUser = form.ownerdepCreateUser ? form.ownerdepCreateUser : ''
        let master = form.master ? form.master : ''

        // 通话特有的
        let disposalAgent = form.DISPOSAL_AGENT ? form.DISPOSAL_AGENT : ''

        // 在线咨询
        let user = form.user ? form.user : ''

        // 邮件
        let agent = form.agent ? form.agent : ''

        return ownercom + owner + ownerdep + ownercomCreateUser + createUser + ownerdepCreateUser + master + disposalAgent + agent + user
      },
      formItems () {
        var formItems = []

        if (this.adv && this.adv.advSearchOptions) {
          var localed = this.adv.advSearchOptions.localed
          var custom = this.adv.advSearchOptions.custom

          var index = 0
          if (localed) {
            localed.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_localed'
              newItem._index = index++
              formItems.push(newItem)
            })
          }

          if (custom) {
            custom.forEach(item => {
              var newItem = deepClone(item)
              newItem._type = '_custom'
              newItem._index = index++
              formItems.push(newItem)
            })
          }
        }

        return formItems
      },
      dealedFormItems () {
        var formItems = deepClone(this.formItems)
        var formItemsConfig = this.editingFormItemsConfig || this.formItemsConfig

        formItems = formItems.filter(item => {
          var shown = true
          var itemName = item.name

          if (item.name.endsWith('_END')) {
            itemName = item.name.replace('_END', '_BEGIN')
          }

          if (formItemsConfig && formItemsConfig[itemName]) {
            var config = formItemsConfig[itemName]
            shown = !config.hidden
          }

          return shown
        })

        formItems.sort((aItem, bItem) => {
          var aOrder
          var bOrder
          var config
          var itemName

          if (aItem.name && aItem.name.endsWith('_END')) {
            itemName = aItem.name.replace('_END', '_BEGIN')
            if (formItemsConfig && formItemsConfig[itemName]) {
              config = formItemsConfig[itemName]
              aOrder = config.order + 0.5
            }
          }

          if (bItem.name && bItem.name.endsWith('_END')) {
            itemName = bItem.name.replace('_END', '_BEGIN')
            if (formItemsConfig && formItemsConfig[itemName]) {
              config = formItemsConfig[itemName]
              bOrder = config.order + 0.5
            }
          }

          if (formItemsConfig && formItemsConfig[aItem.name]) {
            config = formItemsConfig[aItem.name]
            aOrder = config.order
          }

          if (formItemsConfig && formItemsConfig[bItem.name]) {
            config = formItemsConfig[bItem.name]
            bOrder = config.order
          }

          function isNum (n) {
            return !isNaN(n)
          }

          if (isNum(aOrder) && !isNum(bOrder)) {
            return -1
          }

          if (!isNum(aOrder) && isNum(bOrder)) {
            return 1
          }

          if (isNum(aOrder) && isNum(bOrder)) {
            return aOrder - bOrder
          }

          return aItem._index - bItem._index
        })
        return formItems
      }
    },
    filters: {
      sequence: function (value) {
        return value < 9 ? '0' + (value + 1) : (value + 1)
      }
    },
    beforeMount () {
      this.updateGuidanceSuccess()
    },
    mounted () {
      if (this.isCall) {
        this.pickerOptions2.shortcuts.splice(2, 1) // 若是通话，去掉近三个月的搜索
      }
      if (this.isWebchat) {
        let halfYear = {
          text: this.$t('sms.thisHalfYear'),
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182)
            picker.$emit('pick', [start, end])
          }
        }
        this.pickerOptions2.shortcuts.push(halfYear)
      }
      if (this.isShowOneDay) {
        let oneDay = {
          text: this.$t('webchat.oneDay'),
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 24 * 60 * 60 * 1000)
            picker.$emit('pick', [start, end])
          }
        }
        this.pickerOptions2.shortcuts.unshift(oneDay)
      }
      document.addEventListener('click', this.clickFun)
    },
    beforeDestroy () {
      document.removeEventListener('click', this.clickFun)
    }
  }
</script>

<style lang="stylus">
.advanced-search-1
  .el-cascader__search-input
    margin 2px 0 2px 12px
  .webchatFinish
    width 100%
  .el-cascader
    font-size 12px
    line-height 28px
  .el-form-item__label
    display block !important
    padding-bottom 5px !important
    margin-bottom 0px !important
    padding-top 3px !important
  .el-form-item.current-item
    .el-form-item__label
      color #459AE9
  .el-radio
    margin-right 0
  .el-radio + .el-radio
    margin-left 10px
  .el-select__tags
    z-index 10
</style>

<style lang="stylus" scoped>
@import "../../../../assets/common.styl"

@media (max-width: 1440px)
  .popover
    width 860px !important
  .newBusinessSideBar .popover
    left -326px !important
    &:before
      top -7px
      left 332px
    &:after
      top -5px
      left 334px
  .newPublicSideBarSideBar .popover
      left -282px !important
      &:before
       top -7px
       left 288px
      &:after
        top -5px
        left 290px
  .merge .popover
    width 680px !important
  .merge .search-condition
    max-height 200px
  .merge .default-form
      display: inline-block;
      max-width: 680px;
      overflow: hidden;
      white-space break-spaces
.config-button
  border none
  background none
  position absolute
  right 15px
  top 10px
  cursor pointer
  width 20px
  height 20px
  line-height 20px
  z-index 10
  display block
  padding 0
.popover.dialogVisible
  z-index 2003
  .el-form-item
    z-index 16
.form-mark
  position absolute
  border-style solid
  top -1px
  left -1px
  right -1px
  bottom -1px
  background: #000
  opacity 0.15
  z-index 15
  border-radius 4px
  &:before
    content ""
    position absolute
    border-style solid
    top -8px
    left 252px
    border-width 0px 6px 6px 6px
    border-color #000 transparent

.mark
  position absolute
  top -22px
  bottom -4px
  left -4px
  right -4px
  z-index 100
  text-align center
  background rgba(0,0,0,0.03)
  border: dashed 1px #BFBFBF
  border-radius 2px
  line-height 50px
  color #fff
  font-size 26px
  text-shadow 0px 0px 1px #000
  cursor pointer
  &:before
    content ""
    position absolute
    border-style solid
    top -1px
    left -1px
    right -1px
    bottom -1px
    background: #ffffff
    opacity 0.15
    z-index 1
    border-radius 4px
  .sequence
    width 50px
    height 50px
    position absolute
    top calc(50% - 25px)
    left calc(50% - 25px)
    user-select none

.current-item
  .mark
    background rgba(69,154,233,0.15)
    border none

.moving
  .current-item
    .mark
      background rgba(69,154,233,0.2)
.footer-btn-group
  box-shadow 0px -1px 1px 0px rgba(0,0,0,0.1)
  width 100% !important

.el-form-item
  margin-bottom 0
  position relative
  padding 5px 10px
  min-height 51px
  z-index 0
.el-select
  width 100%
.el-checkbox-group
    display flex
    flex-wrap wrap
    margin-top -5px
    .el-checkbox
      margin-left 0
.default-form
  padding-bottom 10px
.fade-enter-active,
.fade-leave-active
  transition all 0.5s ease
.fade-enter,
.fade-leave-active
  opacity 0
.public-to
  color $cf-gray1
  font-size 12px
  margin-left 6px
.high
  position relative
  .el-button
    color $c-main
.high-ranking-search
  padding 30px 0 10px 0
  font-size 0
.search-condition
  max-height calc(100vh - 300px)
  overflow auto
  overflow-x hidden
  margin-left 7px
  margin-right 7px
  padding-bottom 15px
  &::-webkit-scrollbar
    width 6px
    height 6px
.el-form--inline
  .el-form-item
    margin-right 0px
    width 190px
  .add-width
    width 400px
    position relative
  .add-width-linkage
    width 400px
    margin-right 0px
  .minus-width
    width 0px
    .el-form-item__content
      .el-date-editor
        height 30px
        width 384px
  .all-width
    width 100%
  .dotted
    width 100%
    border thin dashed $c-border1
    margin-bottom 15px
  .btn-group
    padding 13px 0 5px 0
    text-align center
  .el-form-item.cdr-call
    width 190px
  .el-form-item.multi-label
    width 190px
.offerTimeWarn
  color $c-pink
  font-size 12px
  position absolute
  top -25px
  left 78px
.popover
  width 1070px
  position absolute
  background $cf-white
  top 36px
  border 1px solid #ddd
  border-radius 4px
  line-height 30px
  box-shadow 0px 2px 4px 0px rgba(0, 0, 0, .12), 0px 0px 6px 0px rgba(0, 0, 0, .04)
  left -250px
  z-index 100
  &:before
   content ""
   position absolute
   border-style solid
   top -6px
   left 254px
   border-width 0px 6px 6px 6px
   border-color #ddd transparent
  &:after
   content ""
   position absolute
   border-style solid
   top -4px
   left 256px
   border-width 0px 4px 4px 4px
   border-color  $cf-white transparent
  .el-button
    color $cf-white
  .rest-btn
    color rgb(31, 61, 58)
    &.is-disabled
      color: #c0c4cc;
  .radioInputwidth
    display: inline-block
    width: 37%
    margin-left: 10px
  .robotSessionTip
    position absolute
    top -25px
    right 90px
    font-size 12px
.disabled
  background-color #F5F7FA
  border-color #E4E7ED
  color #C0C4CC
  cursor not-allowed
/deep/ .default-form .el-select__tags-text {
  display: inline-block;
  max-width: 90px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/deep/ .default-form .el-select .el-tag__close.el-icon-close {
  top: -3px;
}
</style>
